public class MatrixBlockSum {
    // 矩阵区域和 https://leetcode.cn/problems/matrix-block-sum/
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int row=mat.length;
        int col=mat[0].length;
        int[][] dp=new int[row+1][col+1];
        // 先计算出dp数组
        for(int i=1;i<dp.length;i++) {
            for(int j=1;j<dp[0].length;j++) {
                dp[i][j]=dp[i-1][j]+dp[i][j-1]+mat[i-1][j-1]-dp[i-1][j-1];
            }
        }

        // 计算answer数组
        int[][] answer=new int[row][col];
        for(int i=0;i<answer.length;i++) {
            for(int j=0;j<answer[0].length;j++) {
                int x1=Math.max(0,i-k)+1;
                int y1=Math.max(0,j-k)+1;
                int x2=Math.min(answer.length-1,i+k)+1;
                int y2=Math.min(answer[0].length-1,j+k)+1;
                answer[i][j]=dp[x2][y2]-dp[x1-1][y2]-dp[x2][y1-1]+dp[x1-1][y1-1];
            }
        }
        return answer;
    }
}
